package org.vacoor.xqq.ui.comp.richeditor.chooser;

import org.vacoor.xqq.ui.comp.richeditor.Face;

import javax.swing.*;
import javax.swing.text.*;
import java.awt.event.InputMethodEvent;
import java.awt.event.InputMethodListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

/**
 * 表情输入监视器, 负责将输入的表情简码转换为表情
 * <p/>
 * User: vacoor
 */
public class FaceInputMonitor implements InputMethodListener, KeyListener {
    public static final String FACE_PREFIX = "/";
    public static final String ICON_TEXT = " ";

    // 是否正在使用输入法
    private volatile boolean inputMethod;
    private JTextPane textPane;

    public FaceInputMonitor(JTextPane textPane) {
        this.textPane = textPane;
        this.textPane.addInputMethodListener(this);
        this.textPane.addKeyListener(this);
    }

    @Override
    public void inputMethodTextChanged(InputMethodEvent event) {
        inputMethod = (event.getText() != null && 0 == event.getCommittedCharacterCount());
    }

    @Override
    public void caretPositionChanged(InputMethodEvent event) {
    }

    @Override
    public void keyReleased(KeyEvent e) {
        // 如果 JTextPane 为 null 或正在使用输入法 或输入的不是字母
        if (textPane == null || inputMethod || !Character.isLetter(e.getKeyChar())) {
            return;
        }

        StyledDocument doc = textPane.getStyledDocument();
        final int caretPos = textPane.getCaretPosition(); // (不输入字符, 插入符索引为0, 插入一个后为1)
        try {
            // 获取插入符前字符
            final String text = doc.getText(0, caretPos);
            final int prefixIdx = text.lastIndexOf(FACE_PREFIX);

            // 不存在表情简码起始符
            if (0 > prefixIdx) {
                return;
            }
            final String briefCode = text.substring(prefixIdx + 1);
            int idx = FaceUtil.briefCode2Index(briefCode);
            if (idx == -1) {
                return;
            }
            int faceId = FaceUtil.TRANSFER_TABLE[idx];
            Icon face = FaceUtil.faceID2DynamicFace(faceId);

            if (face == null) {
                return;
            }
            SimpleAttributeSet attrSet = new SimpleAttributeSet();
            StyleConstants.setIcon(attrSet, face);
            attrSet.addAttribute(Face.FACE_ID_ATTR_KEY, faceId);

            // 将内容替换为" "(以便删除时按一次 Back 即可删除),并设置文字显示图标
            ((AbstractDocument) doc).replace(prefixIdx, caretPos - prefixIdx, ICON_TEXT, attrSet);
        } catch (BadLocationException ignore) {
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e) {
    }
}
